// pages/reader/reader.js
const app = getApp()
Page({
  data: {
    title: '小说标题',
    content: '',              // 完整文本内容
    currentPageContent: '',   // 当前页内容
    currentPage: 1,          // 当前页码
    totalPages: 1,           // 总页数
    fontSize: 18,            // 字体大小
    fontColor: '#333333',    // 字体颜色
    isNight: false,          // 是否夜间模式
    showSettings: false,     // 是否显示设置面板
    isLoading: true,         // 是否正在加载
    startX: 0, // 触摸开始位置的横坐标
    threshold: 50, // 滑动阈值，这里设为50px，可根据实际情况调整
    currentX: 0, // 当前触摸点的横坐标
    pageNum:0,
    total:0,
    desc:false
  },
  onLoad() {
    const collection = wx.getStorageSync('collection')
    this.setData({
      pageNum:collection.index,
    })
    this.getData({pageNum:collection.index + 1,pageSize:1,collectionId:collection.id})
  },
  getData(obj) {
    this.setData({ isLoading: true })
    setTimeout(() => {
      app.$http.get('/app/media/list', obj).then(res =>{
        this.setData({
          title:res.data.records[0].mediaName,
          total:res.data.total
        })
        wx.request({
          url: 'http://127.0.0.1:9093/media/novel' + res.data.records[0].mediaPath,
          method: 'GET',
          responseType: 'text',
          success: (res) => {
            if (res.statusCode === 200) {
              this.setData({
                content: res.data // 直接获取文本内容
              });
              this.processContent()
            } else {
              wx.showToast({
                title: '获取内容失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '网络错误',
              icon: 'none'
            });
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      })
    },200)
  },

  // 处理文本内容
  processContent() {
    const normalizedContent = this.data.content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
    
    this.setData({ 
      content: normalizedContent
    });
    // 初始化分页
    this.initPagination();
  },

  // 初始化分页
  initPagination() {
    const pages = this.splitContentToPages(this.data.content);
    let pageStart = 0
    if(this.data.desc){
      pageStart = pages.length-1
      this.setData({desc:false})
    }
    this.setData({
      pages,
      currentPage:pageStart + 1,
      totalPages: pages.length,
      currentPageContent: pages[pageStart] || '',
      isLoading:false
    });
    
  },
  // 分页算法
  splitContentToPages(content) {
    const systemInfo = wx.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    const headerHeight = 180;  // 顶部标题栏高度
    const footerHeight = 80;   // 底部控制栏高度
    const padding = 30;       // 内容区域padding

    // 计算可用高度
    const availableHeight = windowHeight - headerHeight - footerHeight - padding * 2;

    // 根据字体大小计算每行高度和每页行数
    const lineHeight = this.data.fontSize * 1.6;
    const linesPerPage = Math.floor(availableHeight / lineHeight);

    // 计算每行大约能容纳的字符数
    const charsPerLine = Math.floor(systemInfo.windowWidth / (this.data.fontSize * 0.6));

    // 按段落处理内容
    const paragraphs = content.split('\n');
    const pages = [];
    let currentPage = '';
    let currentPageLines = 0;
    for (let i = 0; i < paragraphs.length; i++) {
        let para = paragraphs[i].trim();
        if (para === '') {
            continue;
        }
        // 计算段落需要多少行
        const paraLines = Math.ceil(para.length / charsPerLine) || 1;

        // 如果段落能完整放入当前页
        if (currentPageLines + paraLines <= linesPerPage) {
            if (currentPage) {
                // 尝试先加一个换行符，如果放不下再加两个
                if (currentPageLines + 1 + paraLines <= linesPerPage) {
                    currentPage += '\n\n' + para;
                    currentPageLines += 1;
                } else {
                    currentPage += '\n\n' + para;
                    currentPageLines += 2;
                }
            } else {
                currentPage = para;
            }
            currentPageLines += paraLines;
        } 
        // 如果段落太长需要拆分
        else if (paraLines > linesPerPage) {
            // 先把当前页存起来
            if (currentPage) {
                pages.push(currentPage);
                currentPage = '';
                currentPageLines = 0;
            }
            // 拆分长段落
            let remainingText = para;
            while (remainingText) {
                const chunk = remainingText.substring(0, charsPerLine * linesPerPage);
                remainingText = remainingText.substring(charsPerLine * linesPerPage);
                // 确保不在单词中间拆分
                const lastSpace = chunk.lastIndexOf(' ');
                if (lastSpace > 0 && remainingText) {
                    currentPage = chunk.substring(0, lastSpace);
                    remainingText = chunk.substring(lastSpace + 1) + remainingText;
                } else {
                    currentPage = chunk;
                }
                // 尝试将剩余段落的部分内容补充到当前页
                if (remainingText) {
                    const remainingLines = Math.ceil(remainingText.length / charsPerLine);
                    const availableLines = linesPerPage - Math.ceil(currentPage.length / charsPerLine);
                    if (availableLines > 0) {
                        const extraChars = availableLines * charsPerLine;
                        if (remainingText.length > extraChars) {
                            const extraChunk = remainingText.substring(0, extraChars);
                            const lastSpaceInExtra = extraChunk.lastIndexOf(' ');
                            if (lastSpaceInExtra > 0) {
                                currentPage += ' ' + extraChunk.substring(0, lastSpaceInExtra);
                                remainingText = extraChunk.substring(lastSpaceInExtra + 1) + remainingText.substring(extraChars);
                            } else {
                                currentPage += ' ' + extraChunk;
                                remainingText = remainingText.substring(extraChars);
                            }
                        }
                    }
                }
                pages.push(currentPage);
                currentPage = '';
                currentPageLines = 0;
            }
        }
        // 如果段落不能放入当前页，就新建一页
        else {
            if (currentPage) {
                pages.push(currentPage);
            }
            currentPage = para;
            currentPageLines = paraLines;
        }
    }
    // 添加最后一页
    if (currentPage) {
        pages.push(currentPage);
    }
    return pages;
  },

  // 翻页方法
  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({
        currentPage: this.data.currentPage - 1,
        currentPageContent: this.data.pages[this.data.currentPage - 2],
        scrollTop: 0
      });
    }
  },
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({
        currentPage: this.data.currentPage + 1,
        currentPageContent: this.data.pages[this.data.currentPage],
        scrollTop: 0
      });
    }
  },
  // 改变字体大小
  changeFontSize(e) {
    const collection = wx.getStorageSync('collection')
    const newSize = e.detail.value;
    this.setData({ fontSize: newSize }, () => {
      // 字体大小改变后重新分页
      this.initPagination();
    });
  },

  // 切换夜间模式
  toggleNightMode() {
    const isNight = !this.data.isNight;
    this.setData({
      isNight,
      fontColor: isNight ? '#bbbbbb' : '#333333',
      bgColor: isNight ? '#1a1a1a' : '#f5f5f5'
    });
  },
  touchStart(e) {
    this.setData({
      startX: e.touches[0].pageX,
      currentX: e.touches[0].pageX
    });
  },
  touchMove(e) {
    const currentX = e.touches[0].pageX;
    this.setData({
        currentX
    });
    const dx = currentX - this.data.startX;
    if (dx > 50) {
      
      return true
    }
    if(dx < -50){
      
      return true
    }
  },
  touchEnd(e) {
    const collection = wx.getStorageSync('collection')
    const endX = e.changedTouches[0].pageX;
    const dx = endX - this.data.startX;
    if (dx > this.data.threshold) {
      if(this.data.pageNum == 0 && this.data.currentPage == 1){
        wx.showToast({
          title: '已经到头咯~',
          icon: 'none',
          duration: 500
        })
        return false
      }
      if(this.data.currentPage > 1){
        this.prevPage()
        return false
      }
      this.setData({desc:true})
      this.getData({pageNum:this.data.pageNum - 2,pageSize:1,collectionId:collection.id})
      this.setData({pageNum:this.data.pageNum - 1})
      
    }
    if (dx < -this.data.threshold){
      if(this.data.pageNum == this.data.total - 1 && this.data.currentPage == this.data.totalPages){
        wx.showToast({
          title: '已经到头咯~',
          icon: 'none',
          duration: 500
        })
        return false
      }
      if(this.data.currentPage < this.data.totalPages){
        this.nextPage()
        return false
      }
      this.getData({pageNum:this.data.pageNum + 2,pageSize:1,collectionId:collection.id})
      this.setData({pageNum:this.data.pageNum + 1})
    }
  },
  onUnload(){
    let collection = wx.getStorageSync('collection')
    app.$http.get('/app/collection/'+collection.id).then(res=>{
      collection = res.data
      collection.views = collection.views + 1
      app.$http.put('/app/collection/update', collection)
    })
  }
});